<template>
  <div class="home-container">
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchQuery"
            placeholder="搜索文档..."
            clearable
            @keyup.enter="searchDocuments"
          >
            <template #append>
              <el-button :icon="Search" @click="searchDocuments"></el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="16">
          <div class="filter-container">
            <el-select v-model="selectedCategory" placeholder="选择分类" clearable @change="filterByCategory">
              <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-select v-model="selectedTags" multiple collapse-tags placeholder="选择标签" clearable @change="filterByTags">
              <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.id" />
            </el-select>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-divider content-position="left">文档列表</el-divider>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="6" animated />
    </div>
    <div v-else-if="documents.length === 0" class="empty-container">
      <el-empty description="暂无文档" />
    </div>
    <div v-else class="document-list">
      <div v-for="doc in documents" :key="doc.id" class="document-item">
        <el-card class="document-card" shadow="hover">
          <div class="document-header">
            <h3>{{ doc.title }}</h3>
            <div class="document-tags">
              <el-tag v-if="doc.category" size="small" effect="plain">{{ doc.category }}</el-tag>
              <el-tag v-for="tag in doc.tags" :key="tag" size="small" type="info" effect="plain">{{ tag }}</el-tag>
            </div>
          </div>
          <div class="document-content">
            <p>{{ doc.content }}</p>
          </div>
          <div class="document-footer">
            <span>更新时间: {{ new Date(doc.updatedAt).toLocaleString() }}</span>
            <div class="document-actions">
              <el-button size="small" @click="viewDocument(doc.id)">查看</el-button>
              <el-button 
                size="small" 
                type="primary" 
                :icon="doc.subscribed ? Check : Plus"
                @click="toggleSubscription(doc.id)"
              >
                {{ doc.subscribed===1 ? '已订阅' : '订阅' }}
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Check, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 搜索与筛选状态
const searchQuery = ref('')
const selectedCategory = ref('')
const selectedTags = ref([])

// 分页状态
const currentPage = ref(0)
const pageSize = ref(10)
const total = ref(0)

// 数据状态
const loading = ref(true)
const documents = ref([])
const categories = ref([])
const tags = ref([])

// 初始化数据
onMounted(async () => {
  try {
    await Promise.all([
      fetchDocuments(),
      fetchCategories(),
      fetchTags()
    ])
  } catch (error) {
    console.error('Failed to load initial data:', error)
    ElMessage.error('加载数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
})

// 获取文档列表
async function fetchDocuments() {
  // alert(localStorage.getItem('userId'))
  loading.value = true
  try {
    // console.log('Current pageSize:', pageSize.value)
    const response = await axios.get('/api/documents', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        query: searchQuery.value,
        categoryId: selectedCategory.value,
        tags: selectedTags.value.join(','),
        userId: localStorage.getItem('userId') // 添加用户ID
      }
    })
    console.log(response.data)
    
    // 使用实际的API响应数据
    documents.value = response.data.data || []
    total.value = response.data.total || 0
  } catch (error) {
    console.error('Failed to fetch documents:', error)
    ElMessage.error('获取文档列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
async function fetchCategories() {
  try {
    // 这里替换为实际的API调用
    // const response = await axios.get('/api/categories')
    
    // 模拟数据
    categories.value = [
      { id: 1, name: '技术文档' },
      { id: 2, name: '用户手册' },
      { id: 3, name: '产品说明' },
      { id: 4, name: '内部流程' },
      { id: 5, name: '培训资料' }
    ]
  } catch (error) {
    console.error('Failed to fetch categories:', error)
  }
}

// 获取标签列表
async function fetchTags() {
  try {
    // 这里替换为实际的API调用
    // const response = await axios.get('/api/tags')
    
    // 模拟数据
    tags.value = [
      { id: 1, name: 'Vue' },
      { id: 2, name: 'JavaScript' },
      { id: 3, name: '前端' },
      { id: 4, name: 'Java' },
      { id: 5, name: '后端' },
      { id: 6, name: '数据库' }
    ]
  } catch (error) {
    console.error('Failed to fetch tags:', error)
  }
}

// 搜索文档
function searchDocuments() {
  currentPage.value = 1
  fetchDocuments()
}

// 按分类筛选
function filterByCategory() {
  currentPage.value = 1
  fetchDocuments()
}

// 按标签筛选
function filterByTags() {
  currentPage.value = 1
  fetchDocuments()
}

// 查看文档详情
function viewDocument(id) {
  // 实际中这里可能会跳转到文档详情页
  ElMessage.info(`查看文档 ID: ${id}`)
}

// 切换订阅状态
async function toggleSubscription(docId) {
  try {
    // 这里替换为实际的API调用
    const doc = documents.value.find(d => d.id === docId)
    // alert(doc.id)
    if (doc.subscribed) {
      await axios.delete(`/api/subscriptions/document`, {
          userId: localStorage.getItem('userId'),
          documentId:docId
      })
    } else {
      await axios.post('/api/subscriptions/document', { 
        documentId: docId,
        userId: localStorage.getItem('userId')
      })
    }
    
    doc.subscribed = !doc.subscribed
    
    ElMessage.success(doc.subscribed ? '订阅成功' : '已取消订阅')
  } catch (error) {
    console.error('Failed to toggle subscription:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 分页相关
function handleSizeChange(size) {
  pageSize.value = size
  fetchDocuments()
}

function handleCurrentChange(page) {
  currentPage.value = page
  fetchDocuments()
}
</script>

<style scoped>
.home-container {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-section {
  margin-bottom: 20px;
  padding: 0 20px;
}

.filter-container {
  display: flex;
  gap: 10px;
}

.document-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
  padding: 0 20px;
  flex: 0 1 auto;
}

.document-item {
  width: 300px;
  margin-bottom: 20px;
}

.document-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.document-header {
  margin-bottom: 10px;
}

.document-header h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.document-tags {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.document-content {
  flex-grow: 1;
}

.document-content p {
  margin: 0;
  font-size: 14px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.document-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  font-size: 12px;
  color: #909399;
}

.document-actions {
  display: flex;
  gap: 10px;
}

.loading-container,
.empty-container {
  padding: 40px 0;
  text-align: center;
  flex: 1;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-bottom: 20px;
}

.el-divider {
  margin: 0 20px 20px;
}
</style> 